package com.hcc.flow.server.common.utils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.hcc.flow.server.common.vo.SelectCascVO;
import com.hcc.flow.server.common.vo.SelectRelationVO;


@Component
public class AssembleUtil {


	static {
		ConvertUtils.register(new DateConvert(), java.util.Date.class);
		ConvertUtils.register(new DateConvert(), String.class);
	}
	/**
	 * 结构组装
	 * 
	 * @param scenes
	 * @return
	 */
	public static List<SelectRelationVO> selectCheck(List<SelectCascVO> selects) {
		if (CollectionUtils.isEmpty(selects)) {
			return new ArrayList<>();
		}
		Map<String, List<SelectCascVO>> map = selects.stream()
				.collect(Collectors.groupingBy(SelectCascVO::getParentId));
		List<SelectRelationVO> list = new ArrayList<>();
		map.forEach((k, v) -> {
			SelectRelationVO vo = new SelectRelationVO();
			vo.setParentId(k);
			vo.setParentName(v.get(0).getParentName());
			vo.setContent(v);
			list.add(vo);
		});
		return list;
	}
	
	public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
		Map<Object, Boolean> map = new ConcurrentHashMap<>();
		return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
	}

	public static String[] getNullPropertyNames(Object source) {
		final BeanWrapper src = new BeanWrapperImpl(source);
		java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

		Set<String> emptyNames = new HashSet<String>();
		for (java.beans.PropertyDescriptor pd : pds) {
			Object srcValue = src.getPropertyValue(pd.getName());
			if (srcValue == null)
				emptyNames.add(pd.getName());
		}
		String[] result = new String[emptyNames.size()];
		return emptyNames.toArray(result);
	}

	public static void copyProperties(Object src, Object target) {
		BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
	}

}
